<!-- 支付页面,type:默认为产业链，1为购买模块 -->
<template>
  <div class="w-100vwrelative">
    <div class="p-1rem bg-[#eee]">
      <div v-if="type === null">
        <div
          class="bg-white px-1rem py-1rem rounded-1rem"
          v-if="orderData?.receiverAddress"
          @click="showAddress(addressId)"
        >
          <div class="flex justify-between items-center">
            <span
              ><span class="font-bold mr-1rem">{{ orderData?.receiverContact }}</span
              ><span>{{ orderData?.receiverMobile }}</span></span
            >
            <van-icon name="arrow" />
          </div>
          <div class="mt-1rem">{{ orderData?.receiverAddress }}</div>
        </div>
        <div class="bg-white px-1rem py-1rem rounded-1rem" v-else>
          <div class="flex justify-between items-center" @click="showAddress(null)">
            <span><span class="font-bold">请选择收货地址</span></span>
            <van-icon name="arrow" />
          </div>
        </div>
      </div>

      <div class="bg-white px-1rem py-1rem rounded-1rem mt-1rem">
        <div
          v-for="orderItem in orderData.orderList"
          :key="orderItem.id"
          v-if="orderData?.orderList"
        >
          <div
            class="border-b pb-1rem mb-1rem flex flex-between"
            v-for="item in orderItem.orderItemList"
            :key="item.id"
            v-if="orderItem?.orderItemList"
          >
            <van-image
              width="5rem"
              height="5rem"
              :src="item.image"
              fit="cover"
              radius="0.5rem"
              v-if="item?.image"
            />
            <div class="px-0.5rem flex-1">
              <div class="w-full line-clamp-1">
                {{ item.goodsName }}
              </div>
              <div class="w-full text-0.9rem text-[#777] my-0.5rem line-clamp-1">
                <span v-for="(specItem, specIndex) in item.goodsSpec" :key="specItem.id">
                  <span class="mx-0.5rem" v-if="specIndex !== 0">|</span>
                  {{ specItem.valueName }}
                </span>
              </div>
              <div class="w-full">¥ {{ padZeroPrice(item.price) }}</div>
            </div>
            <div class="text-0.8rem h-5rem flex items-end">× {{ item.num }}</div>
          </div>
        </div>
        <div class="flex justify-between w-full">
          <span>商品总价</span>
          <span>¥ {{ padZeroPrice(orderData?.totalFee) }}</span>
        </div>
        <div class="py-0.5rem flex justify-between w-full">
          <span>运费</span>
          <span>¥ 0.00</span>
        </div>
        <div class="flex justify-between w-full text-price_red">
          <span>优惠券</span>
          <span
            ><span class="mr-0.2rem">-</span>¥
            {{ orderData?.preMoney ? padZeroPrice(orderData.preMoney) : '0.00' }}</span
          >
        </div>
      </div>
      <div class="bg-white px-1rem py-1rem rounded-1rem mt-1rem">
        <div class="text-1.1rem font-bold">支付方式</div>
        <div class="flex flex-col pl-1rem pt-1rem">
          <van-radio-group v-model="payType" shape="dot">
            <van-radio :name="1">
              <div class="flex items-center">
                <img
                  src="../../assets/image/pay/wechat_pay.png"
                  class="h-2rem aspect-square mr-0.5rem object-contain"
                />
                <span>微信支付</span>
              </div>
            </van-radio>
            <van-radio :name="2" class="my-1rem">
              <div class="flex items-center">
                <img
                  src="../../assets/image/pay/pocket.png"
                  class="h-2rem aspect-square mr-0.5rem object-contain"
                />
                <span class="text-0.8rem"
                  >余额支付(余额：<span class="text-price_red">￥{{ padZeroPrice(balance) }}</span
                  >)</span
                >
              </div>
            </van-radio>
            <van-radio :name="3" v-show="type == null">
              <div class="flex items-center">
                <img
                  src="../../assets/image/pay/bank.png"
                  class="h-2rem aspect-square mr-0.5rem object-contain"
                />
                <span>对公支付</span>
              </div>
            </van-radio>
          </van-radio-group>
        </div>
      </div>
    </div>
    <div class="sticky bottom-0 left-0 w-100vw bg-white py-10px px-1rem">
      <div class="w-full flex justify-between items-center">
        <span class="">应付金额</span>
        <span class="text-1.1rem font-bold text-price_red"
          >￥ {{ padZeroPrice(orderData?.totalFee) }}</span
        >
      </div>
      <div class="flex justify-center w-full pt-1rem">
        <van-button type="danger" round class="w-90vw" @click="toBuy" :loading="loading">
          {{ '确认支付' }}
        </van-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, inject } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getGoodsByOutTradeNo } from '@/api/goods'
import { getWxPayUrl, balancePay } from '@/api/pay'
import { onActivated } from 'vue'
import { padZeroPrice } from '@/utils/price'
import { showUseAddressBox } from '@/utils/showApi'
import { GetOrderAddressDefault } from '@/api/member'
import { getModuleOrderDetail, updateAddress, updatePayType } from '@/api/order'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const route = useRoute()
const payType = ref(1)
const orderData = ref({})
const addressId = ref()
const type = ref(null)
const balance = ref(0)
const loading = ref(false)
const backToTop = inject('toTop')

// 获取产业链商品订单详情
const initGoods = () => {
  if (route.query.id) {
    const obj = {
      receiverAddress: orderData.value.address,
      receiverContact: orderData.value.contact,
      receiverMobile: orderData.value.phone,
      receiverProvince: orderData.value.provinceId,
      receiverCity: orderData.value.cityId,
    }
    getGoodsByOutTradeNo(route.query.id).then((res) => {
      if (res.code === 20000) {
        orderData.value = {
          ...res.data,
          receiverAddress: res.data?.orderList?.[0].receiverAddress,
          receiverContact: res.data?.orderList?.[0].receiverContact,
          receiverMobile: res.data?.orderList?.[0].receiverMobile,
          receiverProvince: res.data?.orderList?.[0].receiverProvince,
          receiverCity: res.data?.orderList?.[0].receiverCity,
          orderList: res.data.orderList.map((item) => {
            item?.orderItemList?.map((node) => {
              node.goodsSpec = JSON.parse(node.goodsSpec)
              node.spec = JSON.parse(node.spec)
              return node
            })
            return item
          }),
        }
      }
    })
  } else {
    router.push('/')
  }
  if (route.query.address) {
    addressId.value = route.query.address
  } else {
    GetOrderAddressDefault().then((res) => {
      if (res.code === 20000 && res.data && !orderData.value.receiverAddress) {
        orderData.value = {
          ...orderData.value,
          receiverAddress: res.data.address,
          receiverContact: res.data.contact,
          receiverMobile: res.data.phone,
          receiverProvince: res.data.provinceId,
          receiverCity: res.data.cityId,
        }
      }
    })
  }
}

const showPaid = () => {
  showDialog({
    title: '提示',
    message: '你已支付成功，请勿重新支付',
  }).then(() => {
    // on close
    backToTop()
    router.back()
  })
}

// 获取模块订单详情
const initModuleList = () => {
  if (route.query?.id) {
    getModuleOrderDetail(route.query.id).then((res) => {
      if (res.code === 20000) {
        if (res.data.payStatus !== 1) {
          showPaid()
          return
        }
        orderData.value = {
          orderList: [
            {
              orderItemList: res.data.orderItems.map((item) => {
                return {
                  id: item.id,
                  goodsName: item.moduleName,
                  num: 1,
                  price: item.payMoney,
                  goodsSpec: [],
                }
              }),
            },
          ],
          totalFee: res.data.payMoney,
          preMoney: res.data.preMoney,
        }
      }
    })
  }
}

const init = async () => {
  if (!route.query?.type) {
    initGoods()
  } else {
    type.value = route.query.type
    if (route.query?.type === '1') {
      initModuleList()
    }
  }
  const userStore = useUserStore()
  const { balanceMoney } = await userStore.isLogin()
  balance.value = balanceMoney || 0
}

const showAddress = (address) => {
  showUseAddressBox(address, (addressObj) => {
    updateAddress({
      outTradeNo: route.query.id,
      addressId: addressObj.id,
    })
      .then((res) => {
        if (res.code === 20000) {
          showSuccessToast('修改成功')
          orderData.value = {
            ...orderData.value,
            receiverAddress: addressObj.address,
            receiverContact: addressObj.contact,
            receiverMobile: addressObj.phone,
            receiverProvince: addressObj.provinceId,
            receiverCity: addressObj.cityId,
          }
          addressId.value = addressObj.id
        } else {
          showFailToast('修改失败')
        }
      })
      .catch(() => {
        showFailToast('修改失败')
      })
  })
}

// 微信支付
const wxPay = () => {
  getWxPayUrl(
    {
      money: 0.01,
      orderId: route.query.id,
    },
    type,
  ).then((res) => {
    if (res.code === 20000 && res.data?.mweb_url) {
      window.open(res.data?.mweb_url)
    }
  })
}

// 余额支付
const yuePay = () => {
  loading.value = true
  balancePay(
    {
      orderId: route.query.id,
      payAmount: 0.01,
    },
    type,
  )
    .then((res) => {
      if (res.code === 20000) {
        showSuccessToast('支付成功')
        setTimeout(() => {
          router.push('/')
        }, 1000)
      }
    })
    .finally(() => {
      loading.value = false
    })
}

// 确认支付
const toBuy = () => {
  if (payType.value === 1) {
    wxPay()
  } else if (payType.value === 2) {
    if (orderData.value.totalFee >= balance.value) {
      showDialog({
        title: '提示',
        message: '您的余额不足，是否前往充值并购买？',
        showCancelButton: true,
      }).then(() => {
        showDialog({
          title: '提示',
          message: '功能正在完善中...',
        })
        // backToTop()
        // router.push('/module?code=YINGPIN')
      })
    } else {
      yuePay()
    }
  } else if (payType.value === 3) {
    showConfirmDialog({
      title: '提示',
      message: '确定对公支付？',
      beforeClose: toPayByBank,
    })
  }
}

// 对公支付
const toPayByBank = (action) => {
  console.log(action)
  if (action === 'confirm') {
    return new Promise((resolve) => {
      console.log(1)
      updatePayType({
        outTradeNo: route.query.id,
        payType: 6,
      })
        .then((res) => {
          if (res.code === 20000) {
            showDialog({ message: '对公支付成功，请前往后台上传支付凭证' })
            resolve(true)
          }
        })
        .catch(() => {
          resolve(false)
        })
    })
  } else {
    return false
  }
}

init()

onActivated(() => {
  init()
})
</script>
